package com.shushan.pages;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.exam.adapter.ExamFragmentAdapter;
import com.shushan.exam.bean.ExerciseBean;
import com.shushan.exam.bean.ExerciseOptionBean;
import com.shushan.mixedexam.BaseExamFragment;
import com.shushan.mixedexam.oralcalculation.OralCalculationExamFragment;
import com.shushan.mixedexam.oralcalculation.bean.OralCalculateExerciseBean;
import com.shushan.mixedexam.sync.ExamFragment;
import com.shushan.mixedexam.OnAnswerSelectListener;
import com.shushan.mixedexam.bean.MutiExerciseBean;
import com.shushan.mixedexam.bean.MutiExerciseOptionBean;
import com.shushan.mixedexam.bean.MutiExercisePaperBean;
import com.shushan.mixedexam.englishwords.EnglishWordsExam3Fragment;
import com.shushan.mixedexam.englishwords.EnglishWordsExamFragment;
import com.shushan.mixedexam.hearing.HearingExamFragment;
import com.shushan.mixedexam.speaking.SpeakingExamFragment;
import com.shushan.mixedexam.strangewords.StrangeWordsExam2Fragment;
import com.shushan.mixedexam.strangewords.StrangeWordsExamFragment;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.pages.bean.ExerciseRecordDetailsBean;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.util.DownloadUtil;
import com.shushan.util.Session;
import com.shushan.util.ToolUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: RecordDetailActivity
 * @Desciption: 练习详情
 * @author: yichaohua
 * @date: 2018-04-25
 */
public class RecordDetailActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener, OnAnswerSelectListener {

    private static final String TAG = "RecordDetailActivity";

    private ViewPager viewPager;
    private ExamFragmentAdapter examFragmentAdapter;
    private ImageView examButton;
    private TextView examTitleTv, tvCurrentNum, tvTopicTotalNum;
    private Button btnNextTopic;

    private int pageIndex = 0;
    private int practiceType;
    private ExerciseRecordDetailsBean paperBean;
    private boolean isWatchWrongTopic = false;
    private int wrongTopicSize = 0;

    Handler scrollHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:
                    viewPager.setCurrentItem(msg.arg1, true);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.record_detail_activity);

        ScreenManager sm = new ScreenManager();
        if(!sm.setDeepStatusBar(true,this)){
            findViewById(R.id.titlebar_divider).setVisibility(View.GONE);
        }

        paperBean = (ExerciseRecordDetailsBean) Session.getSession().get("paperBean");

        practiceType = getIntent().getIntExtra("practiceType",0);
        isWatchWrongTopic = getIntent().getBooleanExtra("isWatchWrongTopic", false);

        initView();

        initData();
    }

    private void initView() {
        examButton = findViewById(R.id.record_detail_title_img);
        examButton.setOnClickListener(this);
        viewPager = findViewById(R.id.record_detail_vp);
        viewPager.addOnPageChangeListener(this);
        examTitleTv = findViewById(R.id.exam_title_tv);
        tvCurrentNum = findViewById(R.id.tv_current_num);
        tvCurrentNum.setText("(" + 1);
        tvTopicTotalNum = findViewById(R.id.tv_topic_total_num);
        btnNextTopic = findViewById(R.id.btn_next_topic);
        btnNextTopic.setOnClickListener(this);
        btnNextTopic.setEnabled(true);
    }

    private void initData() {
        if (paperBean == null) {
            return;
        }

        examTitleTv.setText(ToolUtils.getExerciseTypeNameByTypeId(practiceType));

        List<Fragment> fragments = new ArrayList<>();
        boolean isOnlyDisplay = true;
        List<MutiExerciseBean> chineseExerciseBeans = paperBean.chineseExerciseBeans;
        List<MutiExerciseBean> mathExerciseBeans = paperBean.mathExerciseBeans;
        List<MutiExerciseBean> englishExerciseBeans = paperBean.englishExerciseBeans;
        if(ToolUtils.isListEmpty(chineseExerciseBeans) && ToolUtils.isListEmpty(mathExerciseBeans)
                && ToolUtils.isListEmpty(englishExerciseBeans)){
            fragments.addAll(getExamFragments(isOnlyDisplay,0,paperBean.exerciseBeans));
        }else {
            if (!ToolUtils.isListEmpty(chineseExerciseBeans)) {
                fragments.addAll(getExamFragments(isOnlyDisplay, 0, chineseExerciseBeans));
            }
            if (!ToolUtils.isListEmpty(mathExerciseBeans)) {
                fragments.addAll(getExamFragments(isOnlyDisplay, fragments.size(), mathExerciseBeans));
            }
            if (!ToolUtils.isListEmpty(englishExerciseBeans)) {
                fragments.addAll(getExamFragments(isOnlyDisplay, fragments.size(), englishExerciseBeans));
            }
        }
        examFragmentAdapter = new ExamFragmentAdapter(this, getSupportFragmentManager(), fragments);
        viewPager.setAdapter(examFragmentAdapter);

        tvTopicTotalNum.setText("/" + fragments.size() + ")");
        showCollect();
    }

    private List<Fragment> getExamFragments(boolean isOnlyDisplay, int beginIndex, List<MutiExerciseBean> exerciseBeans) {
        List<Fragment> fragments = new ArrayList<>();
        if (!ToolUtils.isListEmpty(exerciseBeans)) {
            for (int i = 0; i < exerciseBeans.size(); i++) {
                MutiExerciseBean exerciseBean = exerciseBeans.get(i);
                switch (Integer.parseInt(exerciseBean.exercises_type)) {
                    case Constants.TYPE_SYNC_EXERCISE://同步练习
                        if (isWatchWrongTopic && isExamWrong(exerciseBean)) {
                            ExamFragment syncFragment = ExamFragment.newInstance(isOnlyDisplay, wrongTopicSize++, exerciseBean);
                            syncFragment.setOnAnswerSelectListener(this);
                            fragments.add(syncFragment);
                        } else {
                            ExamFragment syncFragment = ExamFragment.newInstance(isOnlyDisplay, beginIndex + i, exerciseBean);
                            syncFragment.setOnAnswerSelectListener(this);
                            fragments.add(syncFragment);
                        }
                        break;
                    case Constants.TYPE_STRANGE_WORDS_EXERCISE://生字练习
                        if (exerciseBean.exercises_level.equals("1")) {//生字题型2
                            if (isWatchWrongTopic && isExamWrong(exerciseBean)) {
                                StrangeWordsExam2Fragment exam2Fragment = StrangeWordsExam2Fragment.newInstance(isOnlyDisplay, wrongTopicSize++, DownloadUtil.getStrangeWordsExamAudioPath(exerciseBean), exerciseBean);
                                exam2Fragment.setOnAnswerSelectListener(this);
                                fragments.add(exam2Fragment);
                            } else {
                                StrangeWordsExam2Fragment exam2Fragment = StrangeWordsExam2Fragment.newInstance(isOnlyDisplay, i, DownloadUtil.getStrangeWordsExamAudioPath(exerciseBean), exerciseBean);
                                exam2Fragment.setOnAnswerSelectListener(this);
                                fragments.add(exam2Fragment);
                            }
                        } else if (exerciseBean.exercises_level.equals("0")) {//生字题型1
                            if (isWatchWrongTopic && isExamWrong(exerciseBean)) {
                                StrangeWordsExamFragment examFragment = StrangeWordsExamFragment.newInstance(isOnlyDisplay, wrongTopicSize++, exerciseBean);
                                examFragment.setOnAnswerSelectListener(this);
                                fragments.add(examFragment);
                            } else {
                                StrangeWordsExamFragment examFragment = StrangeWordsExamFragment.newInstance(isOnlyDisplay, i, exerciseBean);
                                examFragment.setOnAnswerSelectListener(this);
                                fragments.add(examFragment);
                            }
                        }
                        break;
                    case Constants.TYPE_SPEAKING_EXERCISE://口语练习
                        if (isWatchWrongTopic && isExamWrong(exerciseBean)) {
                            SpeakingExamFragment examFragment = SpeakingExamFragment.newInstance(isOnlyDisplay, wrongTopicSize++, exerciseBean);
                            fragments.add(examFragment);
                        } else {
                            SpeakingExamFragment examFragment = SpeakingExamFragment.newInstance(isOnlyDisplay, i, exerciseBean);
                            fragments.add(examFragment);
                        }
                        break;
                    case Constants.TYPE_ENGLISH_WORDS_EXERCISE://单词练习
                        switch (Integer.parseInt(exerciseBean.exercises_level)) {
                            case 0://题型1
                            case 1://题型2
                            case 3://题型4
                                if (isWatchWrongTopic && isExamWrong(exerciseBean)) {
                                    EnglishWordsExamFragment fragment124 = EnglishWordsExamFragment.newInstance(isOnlyDisplay, wrongTopicSize++, exerciseBean);
                                    fragment124.setOnAnswerSelectListener(this);
                                    fragments.add(fragment124);
                                } else {
                                    EnglishWordsExamFragment fragment124 = EnglishWordsExamFragment.newInstance(isOnlyDisplay, i, exerciseBean);
                                    fragment124.setOnAnswerSelectListener(this);
                                    fragments.add(fragment124);
                                }
                                break;
                            case 2://题型3
                                if (isWatchWrongTopic && isExamWrong(exerciseBean)) {
                                    EnglishWordsExam3Fragment fragment3 = EnglishWordsExam3Fragment.newInstance(this, isOnlyDisplay, wrongTopicSize++, exerciseBean);
                                    fragment3.setOnAnswerSelectListener(this);
                                    fragments.add(fragment3);
                                } else {
                                    EnglishWordsExam3Fragment fragment3 = EnglishWordsExam3Fragment.newInstance(this, isOnlyDisplay, i, exerciseBean);
                                    fragment3.setOnAnswerSelectListener(this);
                                    fragments.add(fragment3);
                                }
                                break;
                        }
                        break;
                    case Constants.TYPE_HEARING_EXERCISE://听力练习
                        HearingExamFragment hearingFragment = HearingExamFragment.newInstance(isOnlyDisplay, i, exerciseBean);
                        hearingFragment.setOnAnswerSelectListener(this);

                        fragments.add(hearingFragment);
                        break;
                }
            }
        }
        return fragments;
    }

    private boolean isExamWrong(MutiExerciseBean exerciseBean) {
        List<MutiExerciseOptionBean> optionList = exerciseBean.getOptionBeans();
        if (optionList == null || optionList.size() == 0) {
            return false;
        }

        for (MutiExerciseOptionBean optionBean : optionList) {
            if (optionBean.id == exerciseBean.my_answer_id && optionBean.option_result == 0) {
                return true;
            }
        }

        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.record_detail_title_img:
                if(examFragmentAdapter.getCount() == 0){
                    return;
                }
                MutiExerciseBean exerciseBean = ToolUtils.getMutiExerciseBean(examFragmentAdapter.getItem(pageIndex));
                if (exerciseBean.child_collect == 1) {
                    doPostCollect(2);
                } else {
                    doPostCollect(1);
                }
                break;
            case R.id.btn_next_topic://跳到下一题
                Message message = scrollHandler.obtainMessage(0);
                message.arg1 = pageIndex + 1;
                scrollHandler.sendMessageDelayed(message, 100);
                tvCurrentNum.setText("(" + (pageIndex + 1));
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onAnswerSelect(int examIndex, boolean isRight) {
        return false;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        pageIndex = position;

        tvCurrentNum.setText("(" + (position + 1));

        showCollect();
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private void showCollect() {
        if(examFragmentAdapter.getCount() == 0){
            return;
        }
        MutiExerciseBean exerciseBean = ToolUtils.getMutiExerciseBean(examFragmentAdapter.getItem(pageIndex));

        if (exerciseBean.child_collect == 1) {
            examButton.setBackgroundResource(R.drawable.exam_title_collected);
        } else {
            examButton.setBackgroundResource(R.drawable.exam_title_uncollect);
        }
    }

    private void dealCollect() {
        if(examFragmentAdapter.getCount() == 0){
            return;
        }
        MutiExerciseBean exerciseBean = ToolUtils.getMutiExerciseBean(examFragmentAdapter.getItem(pageIndex));

        if (exerciseBean.child_collect == 1) {
            examButton.setBackgroundResource(R.drawable.exam_title_uncollect);
            exerciseBean.child_collect = 0;
        } else {
            examButton.setBackgroundResource(R.drawable.exam_title_collected);
            exerciseBean.child_collect = 1;
        }

    }

    /**
     * 收藏和取消收藏
     *
     * @param collectType 1:收藏试题2:取消收藏试题
     */
    private void doPostCollect(final int collectType) {
        if(examFragmentAdapter.getCount() == 0){
            return;
        }
        MutiExerciseBean exerciseBean = ToolUtils.getMutiExerciseBean(examFragmentAdapter.getItem(pageIndex));
        int childId = BabyApplication.getInstance().getCurrentChildId();

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.TOPIC_COLLECT);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id", childId)
                .putValue("exercise_id", exerciseBean.id)
                .putValue("subject_id", exerciseBean.subject_id)
                .putValue("exercises_type", practiceType)
                .putValue("type", collectType + "");

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        dealCollect();
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }
}
